#!/bin/bash
# Restores only the configuration attribute from the supplied ERB 16.1.11.50 ZIP.
# FileWave: run as root after the app payload has been installed, with ERB closed.

exec 1>>/var/log/fwcld.log
exec 2>>/var/log/fwcld.log

set -euo pipefail
# The shared Applications folder serves every user; no login is required.
# Optional first argument overrides the app path for troubleshooting.
if [[ $# -gt 1 ]]; then
  echo "ERROR: Supply at most one app path." >&2
  exit 1
fi
APP="${1:-/Applications/ERB Secure Browser.app}"
echo "Target app: $APP"
ATTR='com.apple.application-instance'
EXPECTED='7777772E7374617274746573742E636F6D5C245C246D61636F73786473625C245C2438305C245C2450524F44554354494F4E5C245C242D315C245C245C245C247777772E70726F6772616D776F726B73686F702E636F6D5C245C242D31'
if [[ ! -d "$APP/Contents" ]]; then
  echo "ERROR: App not found: $APP" >&2
  exit 1
fi
BUNDLE_ID=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$APP/Contents/Info.plist")
if [[ "$BUNDLE_ID" != 'com.testsys.SecureBrowser.ITS' ]]; then
  echo 'ERROR: Unexpected application identity.' >&2
  exit 1
fi
VERSION=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$APP/Contents/Info.plist")
if [[ "$VERSION" != '16.1.11.50' ]]; then
  echo "ERROR: This script is for ERB 16.1.11.50; found $VERSION" >&2
  exit 1
fi
CURRENT=$(/usr/bin/xattr -px "$ATTR" "$APP" 2>/dev/null | /usr/bin/tr -d '[:space:]' || true)
if [[ -n "$CURRENT" && "$CURRENT" != "$EXPECTED" ]]; then
  echo "ERROR: Existing configuration differs; left unchanged for review." >&2
  exit 1
fi
/usr/bin/xattr -wx "$ATTR" "$EXPECTED" "$APP"
ACTUAL=$(/usr/bin/xattr -px "$ATTR" "$APP" | /usr/bin/tr -d '[:space:]')
[[ "$ACTUAL" == "$EXPECTED" ]] || { echo 'ERROR: Verification failed.' >&2; exit 1; }
echo "Verified ERB configuration attribute: $APP"
